// ==UserScript==
// @name         B站一键二连
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @description  try to take over the world!
// @author       Longmo
// @match        https://www.bilibili.com/video/*
// @run-at       document-end
// @grant        GM_addStyle
// ==/UserScript==

(function () {
    'use strict';

    let ops = document.querySelector(".left-container-under-player");

    GM_addStyle('#longmo-show{background:none !important;}')

    const handleClick = () => {
        // alert('点击了！！！')
        const originalElementList = document.querySelectorAll('#arc_toolbar_report .video-toolbar-left-main .toolbar-left-item-wrap');

        //    var clickEvent = new MouseEvent('click', {
        //         bubbles: true,
        //         cancelable: true,
        //         view: unsafeWindow
        //     });
        const el_arc_toolbar_report = document.querySelector('#arc_toolbar_report');
        let el_arc_toolbar_report_Vue=el_arc_toolbar_report.__vue__
        el_arc_toolbar_report_Vue.sendLikeSignal(!el_arc_toolbar_report_Vue.likeSignal)
        // el_arc_toolbar_report_Vue.dialogVisible = true;
        // el_arc_toolbar_report_Vue.dialogType = 'collection'

        el_arc_toolbar_report_Vue.toggleDialog('collection')
        el_arc_toolbar_report_Vue.$forceUpdate();

        // GM_addStyle('.bili-dialog-m{background: none !important;}')
        setTimeout(()=>{
            const el_dialog = document.querySelector('.bili-dialog-m');
            let el_collection = document.querySelector('.collection-m-exp');
            el_dialog.style.visibility = 'hidden';
            el_collection.style.visibility = 'hidden';
            el_dialog.id='longmo-show'
            let el_collection_Vue=  el_collection.__vue__;
            const list = el_collection_Vue.list;
            if(!list){
                console.error('暂无数据list')
            }
            const d =list.find(item=>item.title === '默认收藏夹');
            if(d) {

                if(d.checked){
                    d.favoured=true;
                }
                d.checked=!d.checked;
                el_collection_Vue.submitMove()
                el_dialog.style.visibility = 'auto';
                el_collection.style.visibility = 'auto';
            }
            // 注意这里的时机可稍微长一些，因为弹窗打开后还需要调用接口获取list,待优化
        },1000)


        // const clickEvent = new Event('click', {bubbles: true});
        // 触发的click事件
        // originalElementList[0].dispatchEvent(clickEvent);
        // originalElementList[2].dispatchEvent(clickEvent);
    }

    if (!ops) {
        return
    }

    function addClassAndIncrement(element) {
        if (element) {
            element.classList.add('on');
            const textElement = element.querySelector('.video-toolbar-item-text');
            if (textElement) {
                textElement.innerText = parseInt(textElement.innerText, 10) + 1;
            }
        }
    }

    function triple() {
        let httpRequest = new XMLHttpRequest();
        httpRequest.open('POST', 'https://api.bilibili.com/x/web-interface/archive/like/triple');
        httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpRequest.withCredentials = true;//设置跨域发送带上cookie
        let aid = unsafeWindow.__INITIAL_STATE__.aid;
        let sKey = "bili_jct";
        let csrf = decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
        //上面这一段就是取出csrf，在cookie里面是bili_jct，这一段我是直接copy的，总之获取到就好了啦
        httpRequest.send('aid=' + aid + '&csrf=' + csrf);
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var json = JSON.parse(httpRequest.responseText);
                console.log(json);
                if (json.code == 0) {
                    // alert("三连成功!刷新页面可见");
                    const originalElementList = document.querySelectorAll('#arc_toolbar_report .video-toolbar-left-main .video-toolbar-left-item');
                    if (originalElementList.length >= 3) {
                        // 对列表中的前3个元素执行操作
                        for (let i = 0; i < 3; i++) {
                            // 通过传递选择器字符串到封装的函数来避免代码重复
                            addClassAndIncrement(originalElementList[i]);
                        }
                    } else {
                        console.warn('原始元素列表长度不足3');
                    }
                } else {
                    alert("三连失败/(ㄒoㄒ)/~~");
                }
            }
        };
    }

    ops.addEventListener("DOMNodeInserted", function (event) {
        const originalElement = document.querySelector('#arc_toolbar_report .video-toolbar-left-main .toolbar-left-item-wrap');
        if (!originalElement) {
            return;
        }

        const oldDiv = document.querySelector('#longmo');
        // 已经添加过，则不用再次添加
        if (oldDiv) {
            return;
        }
        const clonedElement = document.createElement("div");
        clonedElement.id = 'longmo'
        clonedElement.innerHTML = originalElement.innerHTML;
        clonedElement.classList = originalElement.classList;

        clonedElement.addEventListener('click', handleClick);
        clonedElement.querySelector('.video-like-info.video-toolbar-item-text').textContent = '一键三连'

        const parentEl = document.querySelector('#arc_toolbar_report .video-toolbar-left-main')
        parentEl.appendChild(clonedElement); // 将复制的元素添加到body中
    });
})();
